import React from 'react'
import './vm_order.module.scss'
import { connect } from 'react-redux';
import { switch_loading } from '../../actions/index';
import { userProps } from '../../interface/user'
import { RouteComponentProps  } from 'react-router-dom'
import { Form, Button, DatePicker, Select, Table, Pagination, message } from 'antd';
import locale from 'antd/es/date-picker/locale/zh_CN'
import { vmOrderList, vmOrderDesktopType, vmOrderListExport, vmOrderTimeCardList } from '../../server/api'
import { PAGE_SIZE, DATE_FORMAT } from '../../config/config'
import { ProductTimeCardItem, vmOrderVmTypeItem } from '../../interface/common'
import moment from 'moment'

const { Option } = Select;
const { RangePicker } = DatePicker;
interface Props {
  user: userProps,
  isShowLoading: Boolean,
  dispatch: Function
}

class VmOrder extends React.Component<RouteComponentProps & Props> {

  state = {
    pageno: 1,
    pagesize: PAGE_SIZE,
    startTime: 0,
    endTime: 0,
    type: '',
    total: 0,
    list: [],
    vmTypeList: [],
    productTimeCardList: [],
    exportParam: {},
    cardName: ''
  }

  componentDidMount () {
    this.getSelectList()
  }

  private handleSubmit () {
    this.setState({
      pageno: 1,
      list: []
    })
    this.getList()
  }

  async getProductTimeCardList(vmType: number, isQueryList = false) {
    let params = {
      xx: new Date().getTime(),
      vmType
    }
    let res = await vmOrderTimeCardList(params)
    if (res.success === 'true') {
      let productTimeCardList = []
      productTimeCardList.push(...res.info.productTimeCardList)
      this.setState({
        productTimeCardList,
        cardName: productTimeCardList.length > 0 ? productTimeCardList[0].cardName : ''
      }, () => {
        if (isQueryList) {
          this.getList()
        }
      })
    } else {
      message.error(res.msg)
    }
  }

  async getSelectList () {
    let params = {
      typeid: 9
    }
    let res = await vmOrderDesktopType(params)
    if (res.success === 'true') {
      this.setState({
        vmTypeList: res.info.productComputerList,
        type: res.info.productComputerList.length > 0 ? res.info.productComputerList[0].vmTypeDes : ''
      }, () => {
        this.getProductTimeCardList(+res.info.productComputerList[0].vmType, true)
      })
    } else {
      message.error(res.msg)
    }
  }

  private async getList () {
    let type = 0
    this.state.vmTypeList.forEach((item: vmOrderVmTypeItem) => {
      if (this.state.type === item.vmTypeDes) {
        type = +item.vmType
      }
    })
    let producttimecardid = 0
    this.state.productTimeCardList.forEach((item: ProductTimeCardItem) => {
      if (this.state.cardName === item.cardName) {
        producttimecardid = item.id
      }
    })

    let params = {
      pageNo: this.state.pageno,
      pageSize: this.state.pagesize,
      startTime: this.state.startTime,
      endTime: this.state.endTime,
      vmType: type,
      producttimecardid
    }
    if (params.pageNo  === 1) {
      this.setState({
        exportParam: params
      })
    }
    this.props.dispatch(switch_loading({show: true}))
    let res = await vmOrderList(params)
    this.props.dispatch(switch_loading({show: false}))
    if (res.success === 'true') {
      res.info.retentionList.forEach((item: any, index: number) => {
        item.key = index
        item.statisticalTime_ = moment(item.statisticalTime).format(DATE_FORMAT)
      })
      this.setState({
        total: res.info.count,
        list: res.info.retentionList
      })
    } else {
      message.error(res.msg)
    }
  }

  private onDateChange (date: any) {
    this.setState({
      startTime: date.length > 0 ? new Date(date[0].format('YYYY/MM/DD') + ' 00:00:00').getTime() : 0,
      endTime: date.length > 0 ? new Date(date[1].format('YYYY/MM/DD') + ' 23:59:59').getTime() : 0
    })
  }

  private sourceChange (type: any) {
    this.setState({
      type
    }, () => {
      let vmType = 0
      this.state.vmTypeList.forEach((item: any) => {
        if (type === item.vmTypeDes) {
          vmType = +item.vmType
        }
      })
      this.getProductTimeCardList(vmType)
    })
  }

  private cardChange (cardName: string) {
    this.setState({
      cardName
    })
  }

  private pageinChange (pageno: number) {
    this.setState({
      pageno
    }, () => {
      this.getList()
    })
  }

  private showSizeChange (current: number, pagesize: number) {
    this.setState({
      pageno: 1,
      pagesize
    }, () => {
      this.getList()
    })
  }

  private async exportList () {
    await vmOrderListExport(this.state.exportParam)
  }

  render () {
    const { list, pageno, total, vmTypeList, type, pagesize, productTimeCardList, cardName } = this.state
    const columns = [
      {
        title: '时间',
        dataIndex: 'statisticalTime_',
        key: 'statisticalTime_',
        // eslint-disable-next-line
        // render: (text: string) => <a>{text}</a>,
      },
      {
        title: '购买主机类型',
        dataIndex: 'vmTypeDes',
        key: 'vmTypeDes',
      },
      {
        title: '购买数量',
        dataIndex: 'buyCount',
        key: 'buyCount',
      },
      {
        title: '套餐包',
        dataIndex: 'setMeal',
        key: 'setMeal',
      }
    ];
    return (
      <div className='user-duration page'>
        <Form layout="inline" onSubmit={this.handleSubmit.bind(this)} className='search'>
          <Form.Item label="时间段">
            <RangePicker locale={locale} onChange={this.onDateChange.bind(this)} placeholder={['开始时间', '结束时间']} format='YYYY-MM-DD'/>
          </Form.Item>
          <Form.Item label='桌面类型'>
            <Select value={type} style={{ width: 120 }} onChange={this.sourceChange.bind(this)}>
              {
                vmTypeList.map((item: vmOrderVmTypeItem) => {
                  return <Option key={item.id} value={item.vmTypeDes}>{item.vmTypeDes}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item label="购买时长">
            <Select value={cardName} style={{ width: 120 }} onChange={this.cardChange.bind(this)}>
              {
                productTimeCardList.map((item: ProductTimeCardItem) => {
                  return <Option key={item.id} value={item.cardName}>{item.cardName}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary"  onClick={this.handleSubmit.bind(this)}>
              搜索
            </Button>
            <Button type="primary" onClick={this.exportList.bind(this)} className='export-btn'>
              导出
            </Button>
          </Form.Item>
        </Form>
        <Table className='table' columns={columns} dataSource={list} pagination={false}/>
        <Pagination className='pagination' current={pageno} total={ total } onShowSizeChange={this.showSizeChange.bind(this)}  onChange={this.pageinChange.bind(this)} pageSize={pagesize} showSizeChanger showQuickJumper showTotal={() => { return `共${total}条数据`}} />
      </div>
    )
  }
}

interface stateType {
  user: userProps,
  isShowLoading: Boolean
}

export default connect(
  (state: stateType) => ({
    user: state.user,
    isShowLoading: state.isShowLoading
  })
)(VmOrder)